<template>
  <div class="guides-manage">
    <div class="page-header">
      <h1 class="page-title">攻略管理</h1>
      <el-button type="primary" @click="handleAdd">
        <el-icon><Plus /></el-icon>
        新增攻略
      </el-button>
    </div>

    <!-- 搜索栏 -->
    <el-card shadow="never" class="search-card">
      <el-form :inline="true" :model="searchForm">
        <el-form-item label="标题">
          <el-input v-model="searchForm.title" placeholder="请输入标题" clearable />
        </el-form-item>
        <el-form-item label="地点">
          <el-input v-model="searchForm.location" placeholder="请输入地点" clearable />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 表格 -->
    <el-card shadow="never" class="table-card">
      <el-table :data="tableData" v-loading="loading" stripe>
        <el-table-column label="封面" min-width="200">
          <template #default="{ row }">
            <el-image :src="row.cover" fit="cover" style="width: 120px; height: 60px; border-radius: 4px;" />
          </template>
        </el-table-column>
        <el-table-column prop="title" label="标题" min-width="200" />
                <el-table-column label="用户" min-width="250">
          <template #default="{ row }">
            <div class="user-info">
              <el-avatar :src="row.author?.avatar || '/logo.svg'" :size="40" />
              <span>{{ row.author?.nickname || '未知用户' }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="统计" width="200">
          <template #default="{ row }">
            <div class="stats">
              <el-tag size="small">浏览: {{ row.viewCount || 0 }}</el-tag>
              <el-tag size="small" type="success">点赞: {{ row.likeCount || 0 }}</el-tag>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" width="180">
          <template #default="{ row }">
            {{ formatTime(row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button link type="primary" size="small" @click="handleView(row)">查看</el-button>
            <el-button link type="primary" size="small" @click="handleEdit(row)">编辑</el-button>
            <el-button link type="danger" size="small" @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.pageSize"
          :total="pagination.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 详情对话框 -->
    <el-dialog v-model="detailVisible" title="攻略详情" width="800px">
      <div v-if="currentRow" class="detail-content">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="标题">{{ currentRow.title }}</el-descriptions-item>
          <el-descriptions-item label="地点">{{ currentRow.location }}</el-descriptions-item>
          <el-descriptions-item label="时长">{{ currentRow.duration }}天</el-descriptions-item>
          <el-descriptions-item label="浏览量">{{ currentRow.viewCount }}</el-descriptions-item>
          <el-descriptions-item label="点赞数">{{ currentRow.likeCount }}</el-descriptions-item>
          <el-descriptions-item label="评论数">{{ currentRow.commentCount }}</el-descriptions-item>
          <el-descriptions-item label="封面" :span="2">
            <el-image :src="currentRow.cover" fit="contain" style="max-width: 300px;" />
          </el-descriptions-item>
          <el-descriptions-item label="标签" :span="2">
            <el-tag v-for="tag in currentRow.tags" :key="tag" size="small">{{ tag }}</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="简介" :span="2">
            {{ currentRow.description }}
          </el-descriptions-item>
          <el-descriptions-item label="内容" :span="2">
            <div class="content-text">{{ currentRow.content }}</div>
          </el-descriptions-item>
        </el-descriptions>
      </div>
    </el-dialog>

    <!-- 编辑对话框 -->
    <el-dialog v-model="editVisible" :title="isEdit ? '编辑攻略' : '新增攻略'" width="800px">
      <el-form :model="formData" :rules="rules" ref="formRef" label-width="100px">
        <el-form-item label="标题" prop="title">
          <el-input v-model="formData.title" placeholder="请输入标题" />
        </el-form-item>
        <el-form-item label="地点" prop="location">
          <el-input v-model="formData.location" placeholder="请输入地点" />
        </el-form-item>
        <el-form-item label="时长(天)" prop="duration">
          <el-input-number v-model="formData.duration" :min="1" />
        </el-form-item>
        <el-form-item label="封面" prop="cover">
          <el-input v-model="formData.cover" placeholder="请输入封面图片URL" />
        </el-form-item>
        <el-form-item label="标签" prop="tags">
          <el-select v-model="formData.tags" multiple placeholder="请选择标签" allow-create filterable>
            <el-option label="美食" value="美食" />
            <el-option label="风景" value="风景" />
            <el-option label="文化" value="文化" />
            <el-option label="摄影" value="摄影" />
          </el-select>
        </el-form-item>
        <el-form-item label="简介" prop="description">
          <el-input v-model="formData.description" type="textarea" :rows="3" placeholder="请输入简介" />
        </el-form-item>
        <el-form-item label="内容" prop="content">
          <el-input v-model="formData.content" type="textarea" :rows="10" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="editVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitLoading">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { getGuidesList, deleteGuide, createGuide, updateGuide } from '@/api/admin'

const loading = ref(false)
const submitLoading = ref(false)
const tableData = ref([])
const detailVisible = ref(false)
const editVisible = ref(false)
const isEdit = ref(false)
const currentRow = ref<any>(null)
const formRef = ref()

const searchForm = reactive({
  title: '',
  location: ''
})

const pagination = reactive({
  page: 1,
  pageSize: 10,
  total: 0
})

const formData = reactive({
  title: '',
  location: '',
  duration: 1,
  cover: '',
  tags: [],
  description: '',
  content: ''
})

const rules = {
  title: [{ required: true, message: '请输入标题', trigger: 'blur' }],
  location: [{ required: true, message: '请输入地点', trigger: 'blur' }],
  content: [{ required: true, message: '请输入内容', trigger: 'blur' }]
}

// 加载数据
const loadData = async () => {
  loading.value = true
  try {
    const params = {
      page: pagination.page,
      pageSize: pagination.pageSize,
      ...searchForm
    }
    const res = await getGuidesList(params)
    console.log(res)
    tableData.value = res.data || []
    pagination.total = res.total || 0
  } catch (error) {
    ElMessage.error('加载数据失败')
  } finally {
    loading.value = false
  }
}

const handleSearch = () => {
  pagination.page = 1
  loadData()
}

const handleReset = () => {
  searchForm.title = ''
  searchForm.location = ''
  handleSearch()
}

const handleAdd = () => {
  isEdit.value = false
  Object.assign(formData, {
    title: '',
    location: '',
    duration: 1,
    cover: '',
    tags: [],
    description: '',
    content: ''
  })
  editVisible.value = true
}

const handleView = (row: any) => {
  currentRow.value = row
  detailVisible.value = true
}

const handleEdit = (row: any) => {
  isEdit.value = true
  currentRow.value = row
  Object.assign(formData, {
    title: row.title,
    location: row.location,
    duration: row.duration,
    cover: row.cover,
    tags: row.tags || [],
    description: row.description,
    content: row.content
  })
  editVisible.value = true
}

const handleDelete = (row: any) => {
  ElMessageBox.confirm('确定删除该攻略吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await deleteGuide(row._id)
      ElMessage.success('删除成功')
      loadData()
    } catch (error) {
      ElMessage.error('删除失败')
    }
  })
}

const handleSubmit = async () => {
  if (!formRef.value) return
  await formRef.value.validate(async (valid: boolean) => {
    if (valid) {
      submitLoading.value = true
      try {
        if (isEdit.value) {
          await updateGuide(currentRow.value._id, formData)
          ElMessage.success('更新成功')
        } else {
          await createGuide(formData)
          ElMessage.success('创建成功')
        }
        editVisible.value = false
        loadData()
      } catch (error) {
        ElMessage.error('操作失败')
      } finally {
        submitLoading.value = false
      }
    }
  })
}

const handleSizeChange = () => {
  loadData()
}

const handleCurrentChange = () => {
  loadData()
}

const formatTime = (timestamp: any) => {
  if (!timestamp) return '-'
  const date = new Date(timestamp)
  return date.toLocaleString('zh-CN')
}

onMounted(() => {
  loadData()
})
</script>

<style scoped lang="scss">
.guides-manage {
  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;

    .page-title {
      font-size: 24px;
      font-weight: 600;
      color: #333;
      margin: 0;
    }
  }

  .search-card {
    margin-bottom: 20px;
  }

  .table-card {
    .stats {
      display: flex;
      gap: 5px;
    }

    .pagination {
      margin-top: 20px;
      display: flex;
      justify-content: flex-end;
    }
  }

  .detail-content {
    .content-text {
      white-space: pre-wrap;
      line-height: 1.6;
    }
  }
}
</style>

